/*
 * grid.cpp
 *
 *  Created on: Nov 4, 2013
 *      Author: kenreurison
 */
#include "grid.h"

grid::grid(int l,int c) {

	numLinhas = l;
	numColunas = c;

	gridAleatorio();
}

void grid::gridAleatorio(){

	srand (time(NULL));
	for(int i=0;i<numLinhas; i++){
		for(int j=0;j<numColunas;j++){
			cell[i][j] = celula(rand() % 2);
		}

	}
}

celula grid::getCell(int i,int j){
	return cell[i][j];
}

int grid::getCellType(int i, int j){
	if(i<numLinhas-1 && i>0){
		if(j<numColunas-1 && j>0){
			//99.9% of type cells
			return CENTER;
		}
	}

	if(i==0){
		if(j<numColunas-1 && j>0){
			return TOP;
		}
	}

	if(j==0){
		if(i<numLinhas-1 && i>0){
			return LEFT;
		}
	}

	if(i==numLinhas-1){
		if(j<numColunas-1 && j>0){
			return BOTTOM;
		}
	}

	if(j==numColunas-1){
		if(i<numLinhas-1 && i>0){
			return RIGTH;
		}
	}

	if(i==0 && j==0){
		return CORNER1;
	}

	if(i==0 && j==numColunas-1){
		return CORNER2;
	}

	if(i==numLinhas-1 && j==numColunas-1){
		return CORNER3;
	}

	if(i==numLinhas-1 && j==0){
		return CORNER4;
	}

	return -100;

}

int grid::numVivosAt(int i, int j){
	int cellType = getCellType(i,j);
	switch (cellType) {
		case CENTER:
			return	cell[i-1][j-1].isAlive()+
						cell[i-1][j].isAlive()+
						cell[i-1][j+1].isAlive()+
						cell[i][j-1].isAlive()+
						cell[i][j+1].isAlive()+
						cell[i+1][j-1].isAlive()+
						cell[i+1][j].isAlive()+
						cell[i+1][j+1].isAlive();
		default:
			break;
	}
	return -100;
}

int** grid::numVivos(){

    int **vivos;
    vivos = (int **)malloc(sizeof(int)*numLinhas);
    for(int i = 0; i < numLinhas; i++) {
    	vivos[i] = (int *)malloc(sizeof(int)*numColunas);
    }
	for(int i=0; i<numLinhas; i++){
			for(int j=0; j<numColunas; j++){
				vivos[i][j] = numVivosAt(i,j);
			}
	}
	return vivos;
}

void grid::showVivos(){
	numVivos();
}

void grid::showGrid(){

	for(int i=0; i<numColunas; i++){
		for(int j=0; j<numLinhas; j++){
			celula c = cell[i][j];
			cout<<c.isAlive()<<" ";
		}
		cout<<endl;
	}
}

grid::~grid() {
	// TODO Auto-generated destructor stub
}
